package com.changgou.seckill.task;

import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.service.SeckillGoodsService;
import com.changgou.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Author: HuangFu
 * @Date: 2020/2/23 9:45
 * @Description:  秒杀商品更新服务
 */
@Component
public class SeckillGoodsPushTask {

    public static final String SECKILL_GOODS_KEY="seckill_goods_";

    public static final String SECKILL_GOODS_STOCK_COUNT_KEY="seckill_goods_stock_count_";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillGoodsService seckillGoodsService;

    /**
     * 定时将秒杀商品存入redis
     * 暂定为30秒一次，正常业务为每天凌晨触发
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void syncSeckillGoods(){
        //获取秒杀时间段
        List<Date> dateMenus = DateUtil.getDateMenus();

        dateMenus.stream().forEach(date -> {
            String keyStr = SECKILL_GOODS_KEY + DateUtil.date2Str(date);
            //获取redis中的数据
            Set keys = redisTemplate.boundHashOps(keyStr).keys();
            //查询当前秒杀商品
            List<SeckillGoods> curSeckillGoods = seckillGoodsService.findCurSeckillGoods(keys, date);
            //将秒杀商品存入缓存
            curSeckillGoods.forEach(seckillGoods -> {
                //存入商品
                redisTemplate.opsForHash().put(keyStr,seckillGoods.getId(),seckillGoods);

                //存入库存数据
                redisTemplate.opsForValue().set(SECKILL_GOODS_STOCK_COUNT_KEY+seckillGoods.getId(),seckillGoods.getStockCount());
            });

        });
    }


}
